﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;

using ProjectBase.Core;

using Survey.Common;
using Survey.Common.Business.Services;
using Survey.Common.Data.Services;
using Survey.Entity.Services;

namespace Survey.Business.Services
{
    public class LanguageFacade : BaseFacade<Language, int, LanguageFilter, ILanguageDao>, ILanguageFacade
    {
        #region IBaseFacade<T> override - FACTORY METHOD
        /// <summary>
        ///     Factory Method pattern.
        ///     Returns new transient entity 'Language'.
        ///     If overriden, some properties could be preset to business defaults.
        ///     (Business rules therefore should be met)
        /// </summary>
        /// <returns>new entity 'Language' transient</returns>
        public override Language CreateNew()
        {
            var entity = new Language();
            // TODO preset entity
            return entity;
        }
        #endregion IBaseFacade<T> override - FACTORY METHOD

        #region constructor
        static LanguageFacade()
        {
            ChangeHandler += Clear;
        }
        #endregion constructor

        #region ILanguageFacade Members
        /// <summary>
        ///     Returns all languages in the system
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<Language> GetAll()
        {
            CheckFileDependency();

            var languages = Languages;
            if (languages.IsNull())
            {
                languages = Dao.GetAll();
                if (languages.IsEmpty())
                {
                    languages = new List<Language> { new Language { LanguageName = "en" } };
                }
                Languages = languages.Select(e => e.Clone() as Language);
            }
            return languages;
        }
        #endregion

        #region Static list
        protected static IEnumerable<Language> Languages { get; set; }

        static void Clear(object sender, EventArgs e)
        {
            Languages = null;
        }
        #endregion Static list

        #region Validation
        public virtual bool IsLanguageNameValid(string languageName)
        {
            if (CultureInfo.GetCultures(CultureTypes.AllCultures)
                .ToList()
                .Any(c => c.Name.Equals(languageName, StringComparison.Ordinal)))
            {
                return true;
            }
            this.PublishError(Str.Messages.LanguageNotExists1
                , languageName);
            return false;
        }
        #endregion Validation
    }
}